package com.example.demo.config;

import com.example.demo.entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Objects;

/**
 * @version 1.0
 * @author： litao
 * @date： 2022-01-25 18:04
 */
//自定义UserRealm 继承extends AuthorizingRealm
public class UserRealm extends AuthorizingRealm {
    private static final transient Logger log = LoggerFactory.getLogger(UserRealm.class);


    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("执行了==>授权doGetAuthorizationInfo");
        log.info("执行了==>授权doGetAuthorizationInfo");

        //SimpleAuthorizationInfo 授权
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermission("user:add");

        //获取当前登录的这个对象
        Subject subject = SecurityUtils.getSubject();

        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了==>认证doGetAuthenticationInfo");
        log.info("执行了==>认证doGetAuthenticationInfo");

        //用户名 密码 数据库中获取
//        String name = "root";
//        String password = "root";

        UsernamePasswordToken userToken = (UsernamePasswordToken) token;

//        User user = userService.queryUserByName(userToken.getUsername());

//        if (Objects.isNull(user)) {
//            //抛出 UnknownAccountException 用户名不存在
//            log.info("UnknownAccountException 用户名不存在");
//            return null;
//        }

        User user = new User();
        Subject currentSubject = SecurityUtils.getSubject();

        Session session = currentSubject.getSession();
        session.setAttribute("loginUser", user);



        //密码认证 shiro做
        return new SimpleAuthenticationInfo(user, user.getPassword(), "");
    }
}
